$(document).ready(function () {

    initSubMenu();
    queryTable();


    layui.use(function () {

        var layer = layui.layer;

        laydate = layui.laydate;

        // 表格
        form = layui.form;

        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.pageSize = 10;
            queryTable()
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        form.on('submit(edit)', function (data) {//监听新增修改提交

            let msgType = "";
            if (curId) {
                msgType = "编辑"
                data.field.id = curId
            } else {
                msgType = "新增"
            }


            new AjaxChain()
                .setUrl('/menu/save')
                .setMethod('post')
                .setData(JSON.stringify(data.field))
                .then(data => {
                    layer.close(drawer);
                    layer.msg(msgType + '成功', { icon: 1, time: 2000 });
                    queryTable()
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


            return false;
        });


    });
})
var params = {};//查询条件参数
var form, unit, laydate;
var drawer;//抽屉实例
var curId = null;//当前选中物资ID
var typeStr = '';//物资类型集合

// 查询表格数据
queryTable = () => {
    let toolWidth = window.innerWidth / 1920 * 320



    layui.use(function () {

        var treeTable = layui.treeTable;

        treeTable.render({

            elem: '#table',
            url: ajaxPrefix() + "/menu/list/all"
            , method: 'get'
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "data": res.result //解析数据列表
                };
            }
            , height: $('.contain-table-list').height()
            , even: true
            , tree: {
                customName: {
                    pid: 'pId',
                    icon: 'xxx',
                },
                data: {
                    isSimpleData: true
                },
                view: {
                    indent: 40,
                    iconLeaf: 'layui-icon layui-icon-file'
                }

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            }
            , cols: [[
                { type: 'space', title: '', width: 50 },
                { field: 'name', title: '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;菜单名称', width: toolWidth*1.5, },
                { field: 'path', title: '路径' },
                {
                    field: 'icon', title: '图标'
                    , templet: function (d) {

                        if (d.icon&&d.icon!='') {
                            return `<img  src="../static/img/menu/${d.icon}"
                              style="width: 0.32rem;height: 0.32rem;cursor: pointer;">`
                        } else{
                            return ''
                        }
                    },
                },
                { field: 'seqId', title: '排序' },
                {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: toolWidth,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool">
                                <div onclick='tableHandle(1,${res})' class="table-edit layui-btn">
                                  <img src="../static/img/edit.png">编辑
                                </div>
                                <div onclick='tableHandle(4,${res})' class="table-record layui-btn">
                                  <img src="../static/img/edit.png">新增子菜单
                                </div>
                                <div onclick='tableHandle(2,${res})' class="table-del layui-btn">
                                  <img src="../static/img/del.png">删除
                                </div>
                              </div>`;
                    },
                },
            ]],


        });

    });

}


// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            openDrawer(2, res)
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/menu/delete')
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增以及菜单 
            curId = null;
            openDrawer(1)
            break;
        case 4://新增子菜单
            curId = null;
            openDrawer(3, res)
            break;


        default:
            break;
    }
}



openDrawer = (type, res) => {
    drawer = layer.open({
        title: (type == 2 ? "编辑" : "新增") + '菜单',
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['30%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'edit-offset',
        success: function (layero, index, that) {
            laydate.render({
                elem: '#expiryDate',
                trigger: 'click',
            });


            if (type == 2) {
                form.val('editForm', res);

            } else {
                form.render(null, 'editForm');
            }

            if (type == 1) {
                form.val('editForm', {
                    pId: null
                });
            } else if (type == 2) {
                form.val('editForm', {
                    pId: res.pId
                });
            } else {
                form.val('editForm', {
                    pId: res.id
                });
            }

        },
        content: `<form class="layui-form layui-form-pane" id="add-form"  lay-filter="editForm"  action="">
                    <div class="form-item layui-hide">
                        <label class="layui-form-label">父级菜单</label>
                        <div class="layui-input-block">
                            <input type="text" name="pId" lay-affix="clear" 
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">路径</label>
                        <div class="layui-input-block">
                            <input type="text" name="path" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">图标</label>
                        <div class="layui-input-block">
                            <input type="text" name="icon" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">排序</label>
                        <div class="layui-input-block">
                            <input type="text" name="seqId" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">描述</label>
                        <div class="layui-input-block">
                            <input type="text" name="description" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item pane-tool" >
                        <button type="reset" class="layui-btn layui-btn-primary btn-reset">重置</button>
                        <button class="layui-btn" lay-submit lay-filter="edit">确认</button>
                    </div>
                </form>`
    });

}